//
//  NSString+VerifyString.m
//  ZKFrameWork
//
//  Created by 熊国兵 on 2018/4/2.
//  Copyright © 2018年 熊国兵. All rights reserved.
//

#import "NSString+VerifyString.h"

@implementation NSString (VerifyString)

- (BOOL)isEmpty {
    if (self == nil || [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]) {
        return YES;
    }
    return NO;
}

//验证邮箱是否合法
- (BOOL)verifyWithEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.([A-Za-z0-9]{2,4})+";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

//验收手机号是否合法
- (BOOL)verifyWithPhone
{
    NSString *emailRegex = @"^1[0-9]{10}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

/**
 验证密码规则

 @return 是否符合规则
 */
- (BOOL)verifyWithPassword
{
    NSString *passwordRegex = @"^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passwordRegex];
    BOOL result = [passwordTest evaluateWithObject:self];
    return result;
}

/**
 * 字母、数字、中文正则判断（不包括空格）
 */
- (BOOL)isInputRuleNotBlank
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5\\d]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}

// 过滤所有表情
- (BOOL)stringContainsEmoji
{
    __block BOOL returnValue = NO;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}

/**
 * 字母、数字、中文正则判断（包括空格)
 */
- (BOOL)isInputRuleAndBlank
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5\\d\\s]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}

- (NSString *)hideFourPhoneNumber
{
    if (self.length != 11) {
        return self;
    }
    NSString * str = [NSString stringWithFormat:@"%@****%@", [self substringToIndex:3], [self substringFromIndex:7]];
    return str;
}


//计算标题文字尺寸
- (CGFloat)calculateTitleWidthWithFont:(UIFont *)font
{
    NSDictionary *dic = @{NSFontAttributeName: font};
    CGSize size = [self boundingRectWithSize:CGSizeMake(kScreenWidth, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size.width;
}

//计算标题文字尺寸
- (CGFloat)calculateTitleHeightWithFont:(UIFont *)font forWith:(CGFloat)width
{
    NSDictionary *dic = @{NSFontAttributeName: font};
    CGSize size = [self boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size.height;
}

- (BOOL)isPhoto
{
    NSArray * arr = @[@"jpg", @"jpeg", @"png", @"bmp", @"gif"];
    NSString * letter = self.lowercaseString;
    for (NSString * name in arr) {
        if ([letter hasSuffix:name]) {
            return YES;
        }
    }
    return NO;
}

- (NSMutableAttributedString *)getRichAttribe:(NSString *)string
{
    NSMutableAttributedString * attr = [[NSMutableAttributedString alloc] initWithString:self];
    if (!string.length) {
        return attr;
    }
    NSRange range = [self rangeOfString:string];
    [attr addAttributes:@{NSForegroundColorAttributeName : ThemeColor} range:range];
    return attr;
}


+ (NSString *)timeWithTimestamp:(double)timestamp
{
    if (timestamp <= 0) {
        return @"";
    }
    NSTimeInterval interval = timestamp / 1000;
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    NSString * time = [formatter stringFromDate:date];
    return time;
}

+ (BOOL)isMoreThanGivenDate:(NSDate *)date
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:[NSDate date]];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date];
    
    return  [comp1 minute] >= [comp2 minute] &&
    [comp1 hour] >= [comp2 hour] &&
    [comp1 day] >= [comp2 day] &&
    [comp1 month] >= [comp2 month] &&
    [comp1 year]  >= [comp2 year];
}


@end
